package com.ext.aic.utils.http;

import android.os.Build;

import java.io.IOException;
import java.util.function.Predicate;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class RetryInterceptor implements Interceptor {
    private final int maxRetries;          // 最大重试次数
    private final Predicate<Response> retryCondition; // 重试条件判断

    // 构造方法（带自定义重试条件）
    public RetryInterceptor(int maxRetries, Predicate<Response> retryCondition) {
        this.maxRetries = maxRetries;
        this.retryCondition = retryCondition;
    }

    // 构造方法（默认重试条件：5xx错误）
    public RetryInterceptor(int maxRetries) {
        this(maxRetries, response -> {
            int code = response.code();
            return code >= 500 && code < 600; // 5xx错误时重试
        });
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = null;
        IOException exception = null;
        int retryCount = 0;

        // 循环尝试请求（初始请求 + 重试）
        while (retryCount <= maxRetries) {
            try {
                response = chain.proceed(request);

                // 判断是否需要重试
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    if (retryCount < maxRetries && retryCondition.test(response)) {
                        response.close(); // 关闭当前响应
                        retryCount++;
                    } else {
                        return response; // 返回成功响应或不再重试的响应
                    }
                }
            } catch (IOException e) {
                exception = e;
                if (retryCount == maxRetries) break; // 达到最大次数时退出
                retryCount++;
            }
        }

        // 所有重试失败后的处理
        if (response != null) return response;
        throw exception != null ? exception : new IOException("Unknown error after " + maxRetries + " retries");
    }
}
